import React, { useState, useRef, useEffect } from 'react';
import { Platform, StyleSheet, Text, Modal as RNModal } from 'react-native';
import {
  Badge,
  Button,
  Flex,
  Tabs,
  Toast,
  Modal,
  WingBlank,
  List,
} from '@ant-design/react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { useNavigation } from '@react-navigation/native';
import FlexTextField from '@/rcomponents/flexTextField';
import { LoadingContainer, Container } from '@/rcomponents/Container';
import { TapRating } from '@/rcomponents/rating';
import { IconX } from '@/rcomponents/iconx';
import { formatDate } from '@/helpers/dateutil';
import UserStore from '@/stores/userStore';
import Card from './components/responsiveCard';
import MaintainJobStore from './maintainJobStore';
import WorkerUserSelectPage from './workerUserSelectPage';
import LmoAddPage from './LmoNrc/lmoSubmitPage';
import NrcAddPage from './LmoNrc/nrcSubmitPage';
import JobCardReportScreen from './jobCard/cardReportView';
import JobCloseModal from './jobCard/maintainJobClose';
import PDFView from 'react-native-view-pdf';
import RNFS from 'react-native-fs';
import { getValue } from '@/services/asyncStorage';
import axios from 'axios';
// import ApiClient from '@/services/apiClient';
import CookieManager from '@react-native-community/cookies';

const styles = StyleSheet.create({
  pwCardTitle: {
    fontWeight: 'bold',
  },
  iconButtonView: {
    flexDirection: 'row',
    //flexGrow: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: 'grey',
    padding: 5,
    borderWidth: 1,
  },
  iconButtonSep: { marginLeft: 5 },
  activeTabText: {
    fontWeight: 'bold',
    fontSize: 20,
    color: 'orange',
  },
  fatherContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    fontWeight: 'bold',
    width: 300,
    lineHeight: 30,
  },
  alertText: {
    fontWeight: 'bold',
    fontSize: 18,
    color: '#191970',
  },
  alertList: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  tabText: Platform.select({
    ios: {
      fontWeight: '200',
    },
    android: {
      color: 'grey',
    },
  }),
});

const MaintenanceSubKinds = [
  {
    title: '航线待执行',
    key: 'flight',
  },
  {
    title: '定检待执行',
    key: 'sc',
  },
  {
    title: '已完成',
    key: 'finished',
  },
];

const isMainState = (item) => {
  return item.planStatus !== 11 && item.planStatus !== 13 && item.ifMain === 1;
};
function MaintenanceJobTab() {
  const [pdfModule, setPdfModule] = useState({
    ifShow: false,
    url: '',
    file: '',
  });
  const [signModal, setSignModal] = useState({
    visible: false,
    item: '',
  });
  const navigation = useNavigation();
  const mjStore = MaintainJobStore.useStore();
  const userStore = UserStore.useStore();
  const closeModalRef = useRef();

  const [tabIndex, setTabIndex] = useState(0);
  const [studentRatingModal, setStudentRatingModal] = useState({
    visible: false,
    taskTid: 0,
    taskStageTid: 0,
    taskStudents: [],
  });

  useEffect(() => {
    console.log('maintenance tab effect');
  }, []);
  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      handleLoadJob();
    });

    return unsubscribe;
  }, [navigation]);
  const handleLoadJob = async () => {
    const res = await mjStore.getJobList(userStore.user.LoginName);
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
    }
  };
  const handleClose = () => {
    setPdfModule({ ...pdfModule, ifShow: false });
  };
  const handleViewTaskCard = (item) => {
    navigation.navigate(JobCardReportScreen.routeName, item);
  };
  const handleViewCard = async (item) => {
    /*
    const authToken = await getValue('auth_token');
    const result = await axios.get(
      `http://testmrs.loongair.cn/FileService${item.jobCardUrl}`,
      {
        responseType: 'blob',
        headers: {
          'Content-type': 'application/pdf',
          Accept: 'application/pdf',
          Authorization: `Bearer ${authToken.access_token}`,
        },
      },
    );
    const res = new Blob([result.data]);
    const timestamp = new Date().getTime(); //获取当前时间错
    const random = String((Math.random() * 1000000) | 0); //六位随机数
    let dirs =
      Platform.OS === 'ios'
        ? RNFS.LibraryDirectoryPath
        : RNFS.ExternalDirectoryPath; //外部文件，共享目录的绝对路径（仅限android）
    const path = `${dirs}/${timestamp + random}.txt`; //下载地址
    RNFS.writeFile(path, res, 'utf8')
      .then((success) => {
        console.log('path', path);
      })
      .catch((err) => {
        console.log(err.message);
      });
      */

    const cookies = await CookieManager.get('https://loongair.cn');
    console.log(
      cookies,
      Object.keys(cookies)
        .map((ck) => `${ck}=${cookies[ck].value}`)
        .join('; '),
    );
    const timestamp = new Date().getTime(); //获取当前时间错
    const random = String((Math.random() * 1000000) | 0); //六位随机数
    let dirs =
      Platform.OS === 'ios'
        ? RNFS.LibraryDirectoryPath
        : RNFS.ExternalDirectoryPath; //外部文件，共享目录的绝对路径（仅限android）
    const downloadDest = `${dirs}/${timestamp + random}.pdf`; //下载地址
    const options = {
      fromUrl: `http://testmrs.loongair.cn/FileService${item.jobCardUrl}`,
      toFile: downloadDest,
      headers: {
        Cookie: Object.keys(cookies)
          .map((ck) => `${ck}=${cookies[ck].value}`)
          .join('; '),
      },
      background: true,
      begin: (res) => {
        // Toast.show('开始下载', Toas  tAndroid.SHORT);
        console.log('begin', res);
        console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
      },
      progress: (res) => {
        //下载进度
        let pro = res.bytesWritten / res.contentLength;
        console.log('pro==', pro);
      },
    };
    try {
      const ret = RNFS.downloadFile(options);
      ret.promise
        .then((res) => {
          console.log('success', res);
          console.log('file://' + downloadDest);
          setPdfModule({
            ...pdfModule,
            ifShow: true,
            file: downloadDest,
          });
        })
        .catch((err) => {
          console.log('err', err);
        });
    } catch (error) {
      console.log(error);
    }
  };
  // console.log(pdfModule.url);
  const handleAssignWorker = (item) => {
    navigation.navigate(WorkerUserSelectPage.routeName, {
      title: '选择工作者',
      type: '4',
      acno: item.acno,
      ifMain: '3', //派工作者
      taskStageTid: item.taskStageTid,
      flightTid: item.flightTid,
      taskTid: [item.id],
    });
  };
  const handleAssignStudent = (item) => {
    navigation.navigate(WorkerUserSelectPage.routeName, {
      title: '选择带教',
      type: '3',
      acno: item.acno,
      ifMain: '2',
      taskStageTid: item.taskStageTid,
      flightTid: item.flightTid,
      taskTid: [item.id],
    });
  };
  const handleTaskSignIn = async (item) => {
    const setPara = {
      taskTid: item.id,
    };
    const res = await mjStore.taskSignIn(userStore.user.LoginName, setPara);
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
    } else {
      handleLoadJob();
      Toast.success('签收成功');
    }
    setSignModal({ visible: false });
  };
  //获取打分情况（打开打分页面按钮）
  const handleStuRateOpen = async (item) => {
    const res = await mjStore.getScoreDetails(userStore.user.LoginName, {
      taskTid: item.id,
    });
    if (res.errorCode) {
      Toast.fail(res.errorMsg.replace(/[\'\"\\\/\b\f\n\r\t]/g, ''));
      return;
    }
    const newStudentRatingModal = {
      visible: true,
      taskTid: item.id,
      taskStageTid: item.taskStageTid,
      taskStudents: [],
    };
    for (let i = 0; i < res.length; i++) {
      newStudentRatingModal.taskStudents.push({
        doTid: res[i].TS_ToTid,
        operatorId: res[i].TS_TaskOperatorId,
        name: res[i].TS_TaskOperatorName,
        rating: res[i].TS_Score,
        flightTid: res[0].TS_Flight_Tid,
      });
    }
    setStudentRatingModal(newStudentRatingModal);
  };
  const handleStuRateClose = () => {
    setStudentRatingModal({
      visible: false,
      taskTid: 0,
      taskStageTid: 0,
      taskStudents: [],
    });
  };
  //保存打分情况（保存打分按钮）
  const handleStuRate = async () => {
    let scorePara = [];
    for (let i = 0; i < studentRatingModal.taskStudents.length; i++) {
      scorePara.push({
        TS_ScoreNow: studentRatingModal.taskStudents[i].scoreNow,
        TS_TasktTid: studentRatingModal.taskTid,
        TS_TaskStageTid: studentRatingModal.taskStageTid,
        TS_Flight_Tid: studentRatingModal.taskStudents[i].flightTid,
        TS_ToTid: studentRatingModal.taskStudents[i].doTid,
        TS_TaskOperatorId: studentRatingModal.taskStudents[i].operatorId,
        TS_TaskOperatorName: studentRatingModal.taskStudents[i].name,
        TS_Score: studentRatingModal.taskStudents[i].rating,
      });
    }
    const res = await mjStore.saveScoreDetails(
      userStore.user.LoginName,
      scorePara,
    );
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
      return;
    }
    handleStuRateClose();
  };
  //进出港到位
  const handleChangeAdStatue = async (item) => {
    const res = await mjStore.changeAdStatus(userStore.user.LoginName, {
      status: item.airportNext,
      tid: item.operatorId,
    });
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
      return;
    } else {
      Toast.success('操作成功');
      return;
    }
  };
  //重新上传
  const handleReUpload = async (item) => {
    const res = await mjStore.ReUploadFile(
      userStore.user.LoginName,
      item.id,
      // formValue.filesUrl,
    );
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
    }
  };
  const renderMtTaskTab = (tab) => {
    return (
      <LoadingContainer
        onRefresh={handleLoadJob}
        loading={mjStore.getJobList.loading}
        data={tab.tasks}
        renderItem={({ item }) => {
          let headerExtra;
          if (tab.key !== 'finished') {
            let addDesc;
            let routeName;
            if (isMainState(item)) {
              if (item.orderType === 'PPC_SC') {
                addDesc = 'NRC编制';
                routeName = NrcAddPage.routeName;
              } else if (item.orderType !== 'NRC') {
                addDesc = 'LMO编制';
                routeName = LmoAddPage.routeName;
              }
            }
            if (addDesc) {
              headerExtra = (
                <Container float="right">
                  <TouchableOpacity
                    style={styles.iconButtonView}
                    onPress={() => {
                      navigation.navigate(routeName, {
                        acno: item.acno,
                        sta: item.airport,
                        taskStageTid: item.taskStageTid,
                        flightTid: item.flightTid,
                        itemNo: item.itemNo,
                        workOrder: item.workOrder,
                        jcCardNo: item.jobCard,
                      });
                    }}
                  >
                    <IconX origin="ant" size={16} name="pluscircleo" />
                    <Text style={styles.iconButtonSep}>{addDesc}</Text>
                  </TouchableOpacity>
                </Container>
              );
            }
          }
          const cardChildren = [
            <Card.Header
              key="header"
              title={
                <Flex style={styles.fatherContainer} numberOfLines={2}>
                  <Text style={styles.pwCardTitle}>
                    {item.cardTitle.replace(/<\/?.+?\/?>/g, '\n')}
                  </Text>
                </Flex>
              }
              extra={headerExtra}
            />,
            <Card.Body key="body">
              <Flex>
                <FlexTextField
                  label="计划"
                  fieldValue={formatDate(item.planDate, 'YYYY-MM-DD HH:mm')}
                />
                <FlexTextField
                  label="完工"
                  fieldValue={formatDate(item.finishDate, 'YYYY-MM-DD HH:mm')}
                />
              </Flex>
              <Flex>
                <FlexTextField label="机号" fieldValue={item.acno} />
                <FlexTextField label="级别" fieldValue={item.taskPaperType} />
              </Flex>
              <Flex>
                <FlexTextField label="状态" fieldValue={item.planStatusDes} />
                <FlexTextField label="站点" fieldValue={item.airport} />
              </Flex>
              <Flex>
                <FlexTextField label="指令号" fieldValue={item.workOrder} />
              </Flex>
              <Flex>
                <FlexTextField label="工作者" fieldValue={item.worker} />
              </Flex>
              {item.taskPaperType !== 'SC' && (
                <Flex>
                  <FlexTextField label="前序航班" fieldValue={item.preflight} />
                </Flex>
              )}
              {item.taskPaperType !== 'SC' && (
                <Flex>
                  <FlexTextField
                    label="后序航班"
                    fieldValue={item.postflight}
                  />
                </Flex>
              )}
              <Flex>
                <FlexTextField label="工卡号" fieldValue={item.jobCard} />
              </Flex>
            </Card.Body>,
          ];
          if (tab.key !== 'finished') {
            const contentBtns = [];
            if (isMainState(item)) {
              contentBtns.push(
                <Button
                  key="worker"
                  type="ghost"
                  size="small"
                  onPress={() => handleAssignWorker(item)}
                >
                  新增工作者
                </Button>,
                <Button
                  key="student"
                  type="ghost"
                  size="small"
                  onPress={() => handleAssignStudent(item)}
                >
                  选带教
                </Button>,
              );
              if (item.planStatus !== 6) {
                if (item.airportNext === '1' || item.airportNext === '3') {
                  contentBtns.push(
                    <Button
                      key="arrive"
                      type="ghost"
                      size="small"
                      onPress={() => handleChangeAdStatue(item)}
                    >
                      进港到位
                    </Button>,
                  );
                }
                if (item.airportNext !== '1' && item.airportNext !== '3') {
                  contentBtns.push(
                    <Button
                      key="depart"
                      type="ghost"
                      size="small"
                      onPress={() => handleChangeAdStatue(item)}
                    >
                      出港到位
                    </Button>,
                  );
                }

                if (item.ifFeedbace !== '0') {
                  contentBtns.push(
                    <Button
                      key="rate"
                      type="ghost"
                      size="small"
                      onPress={() => handleStuRateOpen(item)}
                    >
                      打分
                    </Button>,
                  );
                }
                contentBtns.push(
                  <Button
                    key="close"
                    type="ghost"
                    size="small"
                    onPress={() => closeModalRef.current.show(item)}
                  >
                    关闭
                  </Button>,
                );
              }
            }
            if (item.planStatus === 6 && item.ifMain === 1) {
              contentBtns.push(
                <Button
                  type="ghost"
                  size="small"
                  key="start"
                  onPress={() =>
                    setSignModal({
                      ...signModal,
                      visible: true,
                      item: item,
                    })
                  }
                >
                  签收
                </Button>,
              );
            }
            if (item.planStatus === 11 && item.confirmCloseDDFC === 3) {
              contentBtns.push(
                <Button
                  key="upload"
                  type="ghost"
                  size="small"
                  onPress={() => handleReUpload(item)}
                >
                  重新上传
                </Button>,
              );
            }
            for (let i = 1; i < contentBtns.length; i += 2) {
              contentBtns[i] = (
                <WingBlank key={`wing${i}`}>{contentBtns[i]}</WingBlank>
              );
            }
            cardChildren.push(
              <Card.Footer
                key="footer"
                content={<Flex>{contentBtns}</Flex>}
                extra={
                  item.jobCardUrl && (
                    <Button
                      size="small"
                      type="primary"
                      onPress={() => {
                        handleViewTaskCard(item);
                      }}
                    >
                      工卡
                    </Button>
                  )
                }
              />,
            );
          } else {
            cardChildren.push(
              <Card.Footer
                key="footer"
                extra={
                  item.jobCardUrl && (
                    <Button
                      size="small"
                      type="primary"
                      onPress={() => {
                        handleViewCard(item);
                      }}
                    >
                      工卡查阅
                    </Button>
                  )
                }
              />,
            );
          }
          return <Card key={item.id}>{cardChildren}</Card>;
        }}
      />
    );
  };
  return (
    <>
      <Tabs
        tabs={MaintenanceSubKinds.map((tab, index) => {
          let tasks = mjStore.finishTasks;
          if (tab.key !== 'finished') {
            tasks = mjStore.list[index]; // 返回数据为数组,序号对应
          }
          tasks = tasks || [];
          return {
            key: tab.key,
            tasks,
            title: (
              <Badge text={tasks.length} key={tab.title}>
                <Text
                  style={
                    tabIndex === index ? styles.activeTabText : styles.tabText
                  }
                >
                  {tab.title}
                </Text>
              </Badge>
            ),
          };
        })}
        renderUnderline={() => null}
        page={tabIndex}
        onChange={(_, index) => setTabIndex(index)}
      >
        {renderMtTaskTab}
      </Tabs>
      <Modal
        visible={signModal.visible}
        transparent
        footer={[
          {
            text: '取消',
            onPress: () => {
              setSignModal({ visible: false });
            },
          },
          {
            text: <Text>确定</Text>,
            onPress: () => {
              handleTaskSignIn(signModal.item);
            },
          },
        ]}
      >
        <List style={styles.alertList}>
          <Text style={styles.alertText}>是否确认签收</Text>
        </List>
      </Modal>
      <Modal
        popup
        maskClosable
        animationType="slide-up"
        onClose={handleStuRateClose}
        visible={studentRatingModal.visible}
      >
        <List>
          {studentRatingModal.taskStudents.map((srt) => (
            <List.Item
              key={srt.operatorId}
              extra={
                <TapRating
                  onFinishRating={(pos) => {
                    setStudentRatingModal({
                      ...studentRatingModal,
                      taskStudents: studentRatingModal.taskStudents.map(
                        (item) => {
                          if (item.operatorId === srt.operatorId) {
                            return {
                              ...item,
                              scoreNow: pos,
                            };
                          }
                          return item;
                        },
                      ),
                    });
                  }}
                  showRating={false}
                  defaultRating={srt.rating}
                />
              }
            >
              {srt.name}
            </List.Item>
          ))}
        </List>
        <Button type="primary" onPress={handleStuRate}>
          打分
        </Button>
      </Modal>

      <RNModal visible={pdfModule.ifShow} animationType="slide">
        <PDFView
          fadeInDuration={250.0}
          style={{ flex: 1 }}
          resource={pdfModule.file}
          resourceType={'file'}
          onLoad={() => console.log('PDF rendered from url')}
          onError={(error) => console.log('Cannot render PDF', error)}
        />
        <Button type="primary" onPress={handleClose}>
          关闭
        </Button>
      </RNModal>
      <JobCloseModal ref={closeModalRef} onSubmit={handleLoadJob} />
    </>
  );
}

export default MaintenanceJobTab;
